package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdUserServiceimpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult longin(AdUserDTO dto) {
        //1.参数校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.根据用户查询用户信息
        LambdaQueryWrapper<AdUser> wrapper = Wrappers.lambdaQuery();
        AdUser adUser = getOne(wrapper.eq(AdUser::getName, dto.getName()));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账户或密码是否错误");
        }
        if (9 != adUser.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //3.获取数据库密码和盐
        String password = adUser.getPassword();
        String salt = adUser.getSalt();

        //用户输入密码(加密后)
        String newpassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        if (!password.equals(newpassword)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或密码错误");
        }
        //4.修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5.颁发令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());

        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(adUser, userVO);
        Map map = new HashMap();
        map.put("token", token);
        map.put("user", userVO);
        //6.返回结果
        return ResponseResult.okResult(map);
    }
}
